package com.silverhaze.diamond.server.jms;

import com.silverhaze.diamond.common.constants.DiamondConstants;
import com.silverhaze.diamond.common.event.UIEvent;
import com.silverhaze.diamond.common.util.ServiceLocator;
import org.jboss.xnio.log.Logger;

import javax.jms.*;

/**
 * User: Babanin
 * Date: 16.04.11
 * Time: 19:44
 */
public class UIServerEventDispatcher {
    private static UIServerEventDispatcher instance;

    private Topic topic;
    private Session session;
    private MessageProducer messageProducer;

    public UIServerEventDispatcher() {
        try {
            ConnectionFactory cf = (ConnectionFactory) ServiceLocator.lookup("/ConnectionFactory");

            Connection connection = cf.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            topic = (Topic) ServiceLocator.lookup(DiamondConstants.JMS_DATASOURCE_TOPIC);

            messageProducer = session.createProducer(topic);

            connection.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean notifyEvent(UIEvent event) {
        try {
            Logger.getLogger(UIServerEventDispatcher.class).info(event.toString());
            messageProducer.send(topic, session.createObjectMessage(event));
        } catch (JMSException e) {
            e.printStackTrace();
        }

        return false;
    }

    public static UIServerEventDispatcher getInstance() {
        if (instance == null) {
            instance = new UIServerEventDispatcher();
        }

        return instance;
    }
}
